package com.maisonliberte.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;

import com.maisonliberte.conf.Config;

public class FileUtil {

	public static String getFilename(String path){
		File file = new File(path);
		return file.getName();
	}
	/**
	 * コピー元のパス[srcPath]から、コピー先のパス[destPath]へ
	 * ファイルのコピーを行います。
	 * コピー処理にはFileChannel#transferToメソッドを利用します。
	 * 尚、コピー処理終了後、入力・出力のチャネルをクローズします。
	 * @param srcPath    コピー元のパス
	 * @param destPath    コピー先のパス
	 * @throws IOException    何らかの入出力処理例外が発生した場合
	 */
	public static void copyTransfer(String srcPath, String destPath) 
	    throws IOException {
	    
	    FileChannel srcChannel = new FileInputStream(srcPath).getChannel();
	    FileChannel destChannel = new FileOutputStream(destPath).getChannel();
	    try {
	        srcChannel.transferTo(0, srcChannel.size(), destChannel);
	    } finally {
	        srcChannel.close();
	        destChannel.close();
	    }

	}
	
	public static void removeDIR(String source){
		File[] listFile = new File(source).listFiles(); 
		try{
			if(listFile.length > 0){
				for(int i = 0 ; i < listFile.length ; i++){
					if(listFile[i].isFile()){
						listFile[i].delete(); 
					}else{
						removeDIR(listFile[i].getPath());
					}
					listFile[i].delete();
				}
			}
		}catch(Exception e){
			System.err.println(System.err);
			System.exit(-1); 
		}
			
	}
	
	public static void removeUploadImageFile(String dir){
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/LIST_150px/"));
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/DISPLAY_120px/"));
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/MIDDLE_250px/"));
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/DETAIL_IMG/"));
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/SMALL_80px/"));
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/LARGE_500px/"));
		removeDIR(String.format("%s%s", dir, "/prod_images/stylestore/OTHER_IMG/"));
	}
	
	public static void removeUploadImage(){
		for(int i = 0; i < Config.getInstance().imageRepList.keySet().size(); i++ ){
			removeUploadImageFile(Config.getInstance().imageRepList.get(Config.getInstance().imageRepList.keySet().toArray()[i]));
		}	
	}
	
	public static void writeFile(String data, String filename){
		File file = new File(filename);
		FileWriter filewriter = null;
		try {
			filewriter = new FileWriter(file);
			filewriter.write(data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(filewriter != null){
				try {
					filewriter.close();
					file = null;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
			}
		}
		
	}

}
